#coding=utf-8
import MySQLdb
import sys
import os
import time
from time_format import timestamp_datetime

# get project name
project=''
if __name__=="__main__":
	print sys.argv
	project=sys.argv[1]


#get current time
curTime = time.strftime('%Y-%m-%d',time.localtime(time.time()-60*60*24*7))
print curTime
autherNames = os.popen("git log --pretty='%an' | sort -u")
try:
	conn=MySQLdb.connect(host='120.24.241.79',user='root',passwd='123456',port=3306)
	cur=conn.cursor()
	conn.select_db('gitcount')
	for author in autherNames:
		author = author.replace('\n','').replace('\'','').replace(' ','')
		print author
		if len(author)>0:
			loglistStr = os.popen('git log --since='+curTime+' --author='+author+' --pretty=tformat:"%H,%ad" --date=raw --numstat')
			loglist = loglistStr.read().split('\n')
			
			for log in loglist:
				if len(log)>0:
					if '\t' not in log:
						hash_time=log.replace('"','').replace(' +0800','').split(',')
						hash=hash_time[0]
						com_time=hash_time[1]
					else:
						datas = log.split('\t')
						value=[project,author,hash,int(datas[0]),int(datas[1]),int(datas[0])-int(datas[1]),datas[2],timestamp_datetime(int(com_time))]
						cur.execute('select * from com_data_test where project=%s and hash=%s and file=%s',[project,hash,datas[2]])
						count = int(cur.rowcount)
						if count==0:
							cur.execute('insert into com_data_test(project,author,hash,added,removed,total,file,com_time) values(%s,%s,%s,%s,%s,%s,%s,%s)',value)
							conn.commit()
	cur.close()
	conn.close()
	 
except MySQLdb.Error,e:
	 print "Mysql Error %d: %s" % (e.args[0], e.args[1])
